package cn.wolfcode.wolf2w.util;

import lombok.Getter;
import lombok.Setter;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.Part;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

//图片服务器
@Setter
@Getter
public class FileBean {
    private String fileName;
    private byte[] bytes;

    public String upload(String url) {
        RestTemplate rest = new RestTemplate();
        String fileName = rest.postForObject("Http://" + url + "/fileServer/upload", this, String.class);
        return "Http://" + url + fileName;
    }

    public static FileBean newFileBean(Part part) throws IOException {
        FileBean fileBean = new FileBean();
        InputStream in = part.getInputStream();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        byte[] buff = new byte[1024];
        int len;
        while ((len = in.read(buff)) != -1) {
            os.write(buff, 0, len);
        }

        byte[] bytes = os.toByteArray();
        fileBean.setFileName(part.getSubmittedFileName());
        fileBean.setBytes(bytes);
        return fileBean;
    }
}
